package org.visionlibrary.image.event.executors;

import java.util.ArrayList;
import java.util.Collections;
import java.util.EventListener;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class EventExecutor <V extends EventObject, T extends EventListener> {
	protected boolean __enabled = true;
	protected List<T> __listeners;

	public EventExecutor() {
		__listeners = Collections.synchronizedList(new ArrayList<T>());
	}

	public void addListener(T l) {
		__listeners.add(l);
	}

	public void removeListener(T l) {
		__listeners.remove(l);
	}

	public boolean isEnabled() {
		return __enabled;
	}
	
	public void setEnabled(boolean enabled) {
		__enabled = enabled;
	}
	
	public void __fireEvent(V evt) {
		if(__enabled) {
			synchronized (__listeners) {
				Iterator<T> iterator = __listeners.iterator();
				while (iterator.hasNext()) {
					T listener = iterator.next();
					try {
						__eventExecute(listener, evt);
					} catch (RuntimeException e) {
						Logger log = Logger.getLogger("org.vision-library.event");
						log.log(Level.SEVERE, "event.executor.fireevent.rte");
					}
				}
			}
		}
	}
	
	protected abstract void __eventExecute(T listener, V event);
}
